package com.joysuch.wwyt.bp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.zlg.common.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.attendance.service.AttendanceApiUserService;
import com.joysuch.wwyt.bp.entity.BpJob;
import com.joysuch.wwyt.bp.entity.InspectExceptionAlarmMesage;
import com.joysuch.wwyt.bp.entity.bean.TaskForAssignBean;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigatePlan;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateTask;
import com.joysuch.wwyt.bp.enums.AlarmContentTypes;
import com.joysuch.wwyt.bp.enums.AlarmSourceTypes;
import com.joysuch.wwyt.bp.enums.ExecutiveUnitTypes;
import com.joysuch.wwyt.bp.enums.UnCheckReason;
import com.joysuch.wwyt.bp.mapper.InspectExceptionAlarmMesageMapper;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpInvestigatePlanRepository;
import com.joysuch.wwyt.bp.repository.BpJobDao;
import com.joysuch.wwyt.bp.service.InspectExceptionAlarmMesageService;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.config.RedisClient;
import com.joysuch.wwyt.core.common.util.JsonUtil;
import com.joysuch.wwyt.core.common.util.MapUtils;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.repository.BaseConfigDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.mh.mapper.MhGradingAlarmMapper;
import com.joysuch.wwyt.mh.service.MhGradingAlarmService;
import com.joysuch.wwyt.mh.service.MonitorPointDataWebSocketService;
import com.joysuch.wwyt.monitoringcenter.bean.McAlarmMessageBean;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.entity.RiskPoint;
import com.joysuch.wwyt.risk.service.RiskPointService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.joysuch.wwyt.bp.constant.ProcAlarmDefaultParam.*;
import static com.joysuch.wwyt.bp.constant.ProcAlarmFormAttr.*;
import static com.joysuch.wwyt.bp.constant.ProcAlarmHeaderAttr.SIGNATURE;
import static com.joysuch.wwyt.bp.constant.ProcAlarmHeaderAttr.*;
import static com.joysuch.wwyt.common.constant.Constant.*;
import static com.joysuch.wwyt.core.enums.BaseConfigCodes.*;
import static com.joysuch.wwyt.repeatsubmit.constant.RedisKey.INVES_TIME_OUT_PROCESS_PUSH;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zr
 * @since 2021-11-26
 */
@Slf4j
@Service
public class InspectExceptionAlarmMesageServiceImpl extends ServiceImpl<InspectExceptionAlarmMesageMapper, InspectExceptionAlarmMesage> implements InspectExceptionAlarmMesageService {

    @Autowired
    private InspectExceptionAlarmMesageMapper inspectExceptionAlarmMesageMapper;
    @Autowired
    private RiskPointService riskPointService;
    @Autowired
    private BpInvestigatePlanRepository bpInvestigatePlanRepository;
    @Autowired
    private MonitorPointDataWebSocketService monitorPointDataWebSocketService;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpJobDao bpJobDao;
    @Autowired
    private MhGradingAlarmService mhGradingAlarmService;
    @Autowired
    private MhGradingAlarmMapper mhGradingAlarmMapper;
    @Autowired
    private BaseConfigService baseConfigService;
    @Autowired
    private BpDepartDao departDao;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private BaseConfigDao baseConfigDao;

    @Resource
    private AttendanceApiUserService attendanceApiUserService;

    @Override
    public void saveMessage(Long planId ,Long userId ,Integer contentType ,Long tenentId , String orgCode) {
        saveMessage(planId,userId,null,contentType,tenentId,orgCode);
    }

    @Override
    public void saveMessage(Long planId ,Long userId ,BpInvestigateTask task,Integer contentType ,Long tenentId , String orgCode) {
        InspectExceptionAlarmMesage message = new InspectExceptionAlarmMesage();
        List<Long> userIds = new ArrayList<>();
        StringBuilder detail = new StringBuilder();
        //查询计划
        BpInvestigatePlan plan = bpInvestigatePlanRepository.findFirstById(planId);
        // 分级报警请求参数
        Map<String, Object> processPushParam = null;
        //老任务与新任务分开处理
        if (plan.getSourceType() == 0){
            message.setAlarmTime(DateTime.now());
            message.setState(0);
            userIds.add(userId);
            if (CollectionUtils.isNotEmpty(userIds)){
                message.setInspectUser(JSON.toJSONString(userIds));
            }
            String realName = baseUserDao.getRealNameById(userId);
            message.setMonitoringType(AlarmSourceTypes.CONTENT_ABNORMAL.getCode());
            detail.append(Constant.COLON_ENGLISH).append(plan.getCheckPlanName()).append(Constant.COLON_ENGLISH).append(realName).append(AlarmContentTypes.INVESTIGATE_FIND_EXCEPTION.getValue());
        }else {
            //根据计划id找到风险点id
            Long pointId = plan.getRiskPointId();
            if (pointId == null){
                pointId = inspectExceptionAlarmMesageMapper.getRiskPointByplanId( plan.getRiskPointId());
                if(pointId == null) {
                    throw new IllegalArgumentException("未查询到风险点,请检查");
                }
            }
            RiskPoint riskPoint = riskPointService.findByIdIgnoreDeleteStatus(pointId);
            String pointName = riskPoint.getName();
            message.setRiskPointId(pointId);
            message.setAlarmTime(DateTime.now());
            message.setState(0);
            //userIds,签到和上报异常都是单人,过期未检查是全部人员(此时传过来为null自己查找对应人员)
            //contentType,报警内容类型不同则报警信息不同
            if(AlarmContentTypes.INVESTIGATE_FIND_EXCEPTION.getCode().equals(contentType)){
                message.setMonitoringType(AlarmSourceTypes.CONTENT_ABNORMAL.getCode());
                userIds.add(userId);
                if (CollectionUtils.isNotEmpty(userIds)){
                    message.setInspectUser(JSON.toJSONString(userIds));
                }
                String realName = baseUserDao.getRealNameById(userId);
                detail.append(Constant.COLON_ENGLISH).append(pointName).append(Constant.COLON_ENGLISH).append(realName).append(AlarmContentTypes.INVESTIGATE_FIND_EXCEPTION.getValue());
            }else if (AlarmContentTypes.INVESTIGATE_SIGN_IN_EXCEPTION.getCode().equals(contentType)){
                message.setMonitoringType(AlarmSourceTypes.SIGN_IN_ABNORMAL.getCode());
                userIds.add(userId);
                if (CollectionUtils.isNotEmpty(userIds)){
                    message.setInspectUser(JSON.toJSONString(userIds));
                }
                String realName = baseUserDao.getRealNameById(userId);
                detail.append(Constant.COLON_ENGLISH).append(pointName).append(Constant.COLON_ENGLISH).append(realName).append(AlarmContentTypes.INVESTIGATE_SIGN_IN_EXCEPTION.getValue());
            }else if (AlarmContentTypes.EXPIRED_INVESTIGATE.getCode().equals(contentType)){
                // fix: 27802
                if (DeleteFlag.DELETED.getCode().equals(riskPoint.getDeleteFlag())) {
                    return;
                }
                message.setMonitoringType(AlarmSourceTypes.OVERDUE_UNCHECKED.getCode());
                List<Long> assignList = null;
                String userNames = null;
                if (ExecutiveUnitTypes.USER.getCode().equals(plan.getExecutiveUnit())){
                    // 准备assign数据，通过排班模块过滤
                    if (task == null){
                        return;
                    }
                    TaskForAssignBean assignBean = new TaskForAssignBean(task.getId(),task.getCheckDate(),JSON.parseArray(plan.getExecutor(), Long.class));
                    List<TaskForAssignBean> assignBeans = new ArrayList<>();
                    assignBeans.add(assignBean);
                    // 排班过滤分配人
                    assignBeans = attendanceApiUserService.batchUserTaskCheck(assignBeans);
                    if (CollectionUtils.isEmpty(assignBeans)){
                        return;
                    }
                    assignList = assignBeans.get(0).getAssignList();
                    userNames = setInspectUserAndGetUserNames(JSON.toJSONString(assignList), message);
                    if (StringUtils.isBlank(userNames)){
                        return;
                    }
                    detail.append(Constant.COLON_ENGLISH).append(pointName).append(Constant.COLON_ENGLISH).append(userNames)
                            .append("(").append(plan.getCheckRateDescribe()).append(")").append(AlarmContentTypes.EXPIRED_INVESTIGATE.getValue());
                }else if (ExecutiveUnitTypes.JOB.getCode().equals(plan.getExecutiveUnit())){
                    BpJob job = bpJobDao.findOneById(plan.getUnitId());
                    if (job == null){
                        return;
                    }
                    List<BaseUser> users = baseUserDao.findByJob(plan.getUnitId());
                    if (CollectionUtils.isEmpty(users)){
                        return;
                    }
                    String inspectUsers = JSON.toJSONString(users.stream().map(BaseUser::getId).collect(Collectors.toList()));
                    message.setInspectUser(inspectUsers);
                    String jobName = bpJobDao.findNameById(plan.getUnitId());
                    detail.append(Constant.COLON_ENGLISH).append(pointName).append(Constant.COLON_ENGLISH).append(jobName)
                            .append("(").append(plan.getCheckRateDescribe()).append(")").append("岗位排查").append(AlarmContentTypes.EXPIRED_INVESTIGATE.getValue());
                    List<BaseUser> assigns = baseUserDao.findByJob(plan.getUnitId());
                    if (CollectionUtil.isNotEmpty(assigns)) {
                        assignList = assigns.stream().map(BaseUser::getId).collect(Collectors.toList());
                        userNames = assigns.stream().map(BaseUser::getRealName).collect(Collectors.joining(SPLIT_COMMA));
                    }
                }
                processPushParam = buildGradingAlarmParam(detail.toString(), assignList, userNames, task.getId(), riskPoint);
                message.setTenentId(tenentId);
                message.setOrgCode(orgCode);
            }
        }
        message.setDetail(detail.toString());
        inspectExceptionAlarmMesageMapper.insert(message);
        //产生报警立即向WebSocket推送报警信息
        monitorPointDataWebSocketService.getInspectAlarmMessage(Lists.newArrayList(message),"ADD",tenentId,orgCode);
        // 未检信息放入redis，等待发起分级报警
        if (processPushParam != null) {
            processPushParam.put(DATA_SOURCE_ID, message.getId());
            processPushParam.put(BUS_TYPE, "INVES_TASK_TIME_OUT_ALARM");
            redisClient.hput(INVES_TIME_OUT_PROCESS_PUSH, message.getId(), JSON.toJSONString(processPushParam));
        }
    }

    @Override
    public void setAllMeaageHandled(String msg, String alarmReason, Long handleBy, Date handleTime) {
        inspectExceptionAlarmMesageMapper.setAllMeaageHandled(msg,alarmReason,handleBy,handleTime);
    }

    @Override
    public List<McAlarmMessageBean> queryInspectException(Integer state , Long tenentId , String orgCode) {
        List<McAlarmMessageBean> result = new ArrayList<>();
        LambdaQueryWrapper<InspectExceptionAlarmMesage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InspectExceptionAlarmMesage :: getDeleteFlag , DeleteFlag.EFFECTIVE.getCode())
                .eq(state != null,InspectExceptionAlarmMesage :: getState , state)
                .eq(tenentId != null,InspectExceptionAlarmMesage :: getTenentId ,tenentId)
                .likeRight(StringUtils.isNotBlank(orgCode),InspectExceptionAlarmMesage :: getOrgCode,orgCode)
                .orderByDesc(InspectExceptionAlarmMesage :: getAlarmTime)
                 .last("limit 100")
                 ;
        List<InspectExceptionAlarmMesage> inspectExceptionAlarmMesages = inspectExceptionAlarmMesageMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(inspectExceptionAlarmMesages)){
            result = convert(inspectExceptionAlarmMesages);
        }
        return result;
    }


    /**
     *  转换为前端通用格式
     * @param messages
     * @return
     */
    private List<McAlarmMessageBean> convert(List<InspectExceptionAlarmMesage> messages){
        List<McAlarmMessageBean> result = new ArrayList<>();
        for (InspectExceptionAlarmMesage message : messages) {
            McAlarmMessageBean bean = new McAlarmMessageBean();
            bean.setClassify("巡检排查");
            bean.setId(message.getId());
            bean.setRiskDistrictId(message.getRiskPointId());
            bean.setType("巡检排查");
            if (AlarmSourceTypes.OVERDUE_UNCHECKED.getCode().equals(message.getMonitoringType())){
                bean.setTitle(AlarmSourceTypes.OVERDUE_UNCHECKED.getValue());
            }else if (AlarmSourceTypes.SIGN_IN_ABNORMAL.getCode().equals(message.getMonitoringType())){
                bean.setTitle(AlarmSourceTypes.SIGN_IN_ABNORMAL.getValue());
            }else if (AlarmSourceTypes.CONTENT_ABNORMAL.getCode().equals(message.getMonitoringType())){
                bean.setTitle(AlarmSourceTypes.CONTENT_ABNORMAL.getValue());
            }
            bean.setContent(message.getDetail());
            bean.setState(message.getState());
            bean.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(message.getAlarmTime()));
            if (AlarmSourceTypes.CONTENT_ABNORMAL.getCode().equals(message.getMonitoringType())){
                bean.setAlarmLevel(AlarmSourceTypes.CONTENT_ABNORMAL.getValue());
            }else if (AlarmSourceTypes.SIGN_IN_ABNORMAL.getCode().equals(message.getMonitoringType())){
                bean.setAlarmLevel(AlarmSourceTypes.SIGN_IN_ABNORMAL.getValue());
            }else if (AlarmSourceTypes.OVERDUE_UNCHECKED.getCode().equals(message.getMonitoringType())){
                bean.setAlarmLevel(AlarmSourceTypes.OVERDUE_UNCHECKED.getValue());
            }
            if (message.getRiskPointId() != null){
                RiskPoint riskPoint = riskPointService.findByIdIgnoreDeleteStatus(message.getRiskPointId());
                if (null != riskPoint && StringUtils.isNotBlank(riskPoint.getCenterPoint())){
                    //计算中心点
                    MapUtils.SafetyPoint centerPoint = JsonUtil.fromJson(riskPoint.getCenterPoint(), MapUtils.SafetyPoint.class);
                    bean.setX(centerPoint.getX());
                    bean.setY(centerPoint.getY());
                    bean.setZ(centerPoint.getZ());
                    bean.setFloorId(riskPoint.getFloorId());
                }
            }
            result.add(bean);
        }
        return result;
    }

    /**
     * 将人员ids转为人员姓名用逗号分割
     * @param executorStr
     * @return
     */
    private String setInspectUserAndGetUserNames(String executorStr, InspectExceptionAlarmMesage message) {
        if (StringUtils.isBlank(executorStr)) {
            return null;
        }
        List<Long> executorIds = JSONArray.parseArray(executorStr, Long.class);
        // 过滤掉删除的人
        List<BaseUser> users = baseUserDao.getAllByIdsAndShowState(executorIds);
        if (CollectionUtil.isNotEmpty(users)) {
            message.setInspectUser(JsonUtil.toJson(users.stream().map(BaseUser::getId).collect(Collectors.toList())));
            String userNamesStr = users.stream().map(BaseUser::getRealName).collect(Collectors.joining(SPLIT_COMMA_FULL_WIDTH));
            if (StringUtils.isNotBlank(userNamesStr)) {
                return userNamesStr;
            }
        }
        return null;
    }


    @Override
    public List<InspectExceptionAlarmMesage> statsForCountInDay(LocalDateTime startTime,Long tenentId, String orgCode) {
        Date date = Date.from( startTime.atZone( ZoneId.systemDefault()).toInstant());
        return inspectExceptionAlarmMesageMapper.statsForCountInDay(date,tenentId,orgCode);
    }

    private Map<String, Object> buildGradingAlarmParam(String alarmInfo, List<Long> assignIds, String assignNames, Long taskId, RiskPoint riskPoint) {
        BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.OPEN_HD_TIME_OUT_GRADE_ALARM);
        if (config == null || !COMMON_SWITCH_ON.equals(config.getValue())) {
            return null;
        }
        // 表单数据
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put(ALARM_TIME, SimpleDateFormatCache.getYmdhms().format(new Date())); // 报警时间
        requestBody.put(ALARM_INFO, alarmInfo);
        requestBody.put(ASSIGN_USER, assignIds.stream().map(String::valueOf).collect(Collectors.joining(SPLIT_COMMA))); // 排查人员
        requestBody.put(ASSIGN_USER_NAME, assignNames.replaceAll(SPLIT_COMMA_FULL_WIDTH, SPLIT_COMMA)); // 排查人员名称 中文逗号更换为应为逗号
        requestBody.put(ALARM_TYPE_NAME, UnCheckReason.TO.getValue()); // 报警类型
        requestBody.put(ALARM_TYPE, UnCheckReason.TO.getCode()); // 报警类型
        requestBody.put(TASK_ID, taskId); // 任务id
        requestBody.put(RISK_POINT, riskPoint.getName()); // 风险单元名称
        BaseUser responsibleUser = riskPoint.getResponsibleUser();
        if (Objects.nonNull(responsibleUser)) {
            requestBody.put(POINT_RESP_USER, responsibleUser.getId()); // 分析单元责任人
            requestBody.put(POINT_RESP_USER_NAME, responsibleUser.getRealName());
        }
        RiskDistrict riskDistrict = riskPoint.getRiskDistrict();
        if (Objects.nonNull(riskDistrict)) {
            requestBody.put(RISK_DIST, riskDistrict.getId()); // 风险对象
            requestBody.put(RISK_DIST_NAME, riskDistrict.getName());
        }
        requestBody.put(RISK_LEVEL, riskPoint.getRiskLevel());
        Long distRespDeptId = riskDistrict.getResponsibleDept();
        requestBody.put(POINT_DEPT, distRespDeptId);
        requestBody.put(POINT_DEPT_NAME, departDao.getNameById(distRespDeptId));
        return requestBody;
    }

    /**
     * 隐患排查任务未检分级报警推送
     */
    @Scheduled(fixedDelay = 1000 * 60)
    public void pushInvesTaskTimeOutProcess() {
        RMap<String, String> rMap = redisClient.getMap(INVES_TIME_OUT_PROCESS_PUSH);
        if (CollectionUtil.isEmpty(rMap)) {
            return;
        }
        // 流程定义、appId、签名、流程引擎地址缓存 key:tenantId + : + orgCode
        HashMap<String, String> processDefKeyMap = new HashMap<>();
        HashMap<String, String> appIdMap = new HashMap<>();
        HashMap<String, String> signatureMap = new HashMap<>();
        HashMap<String, String> workFlowIpAddressMap = new HashMap<>();

        if (CollectionUtil.isNotEmpty(rMap)) {
            for (String alarmId : rMap.keySet()) {
                String processPushParamCache = rMap.get(alarmId);
                try {
                    Long messageId = Long.valueOf(alarmId);
                    InspectExceptionAlarmMesage alarmMessage = this.getById(messageId);
                    // 分级报警流程定义key等配置信息
                    String processDefKey = getConfigByCode(alarmMessage.getTenentId(), alarmMessage.getOrgCode(), processDefKeyMap, YH_TimeOut_ProcessDefKey, null);
                    String appId = getConfigByCode(alarmMessage.getTenentId(), alarmMessage.getOrgCode(), appIdMap, APPID, null);
                    String signature = getConfigByCode(alarmMessage.getTenentId(), alarmMessage.getOrgCode(), signatureMap, SIGNATURE, null);
                    // 流程引擎地址非必填，默认127.0.0.1:8886
                    String workFlowIpAddr = getConfigByCode(alarmMessage.getTenentId(), alarmMessage.getOrgCode(), workFlowIpAddressMap, WORKFLOW_IP_ADDRESS, DEFAULT_WF_IP_ADDR);
                    String fullUrl = workFlowIpAddr + DEFAULT_WF_START_PROC_URL;
                    JSONObject paramJsonObj = JSON.parseObject(processPushParamCache);
                    HashMap<String, Object> reqBody = new HashMap<>(paramJsonObj);
                    reqBody.put(PROCESS_DEF_KEY, processDefKey);
                    // 构建请求头
                    Map<String,String> header = buildHeader(appId, alarmMessage, signature);

                    // 发起流程
                    String response = HttpRequest.post(fullUrl).headerMap(header, false).body(JSONUtil.toJsonStr(reqBody)).execute().body();

                    // 处理请求结果
                    JSONObject respBody = JSONObject.parseObject(response);
                    // 请求失败
                    if (!String.valueOf(respBody.get(ATTRIBUTE_CODE)).equals(BaseConfigCodes.MH_GRADING_ALARM_CODE)) {
                        throw new RuntimeException(String.format("隐患未检分级报警流程发起失败:[%s]", respBody));
                    }
                    // 未返回流程实例id
                    if (ObjectUtils.isEmpty(respBody.get(ATTRIBUTE_DATA)) || Constant.EMPTY_STR.equals(String.valueOf(respBody.get(ATTRIBUTE_DATA)))) {
                        throw new RuntimeException(String.format("隐患未检分级报警流程发起失败:[%s]", respBody));
                    }
                    String processInstId = String.valueOf(respBody.get(ATTRIBUTE_DATA));
                    alarmMessage.setProcInstId(processInstId);
                    this.updateById(alarmMessage);
                    redisClient.removeMapKey(INVES_TIME_OUT_PROCESS_PUSH, alarmId);
                }catch (Exception ignore) {
                    log.error("隐患未检分级报警流程发起失败，报警id：{}", alarmId, ignore);
                }
            }
        }
    }

    private String getConfigByCode(Long tenantId, String orgCode, Map<String, String> configMap, String code, String defaultValue) {
        String configValue = configMap.get(tenantId + SPLIT_COLON + orgCode);
        if (StringUtils.isBlank(configValue)) {
            BaseConfig baseConfig = baseConfigDao.findByTenentIdAndOrgCodeAndCode2(tenantId, orgCode, code);
            // 未配置
            if (ObjectUtils.isEmpty(baseConfig) || StringUtils.isBlank(baseConfig.getValue())) {
                if (defaultValue == null) { // 无默认值直接抛异常
                    throw new RuntimeException(String.format("分级报警配置错误：%s，租户：%s", code, tenantId));
                }else { // 使用默认值
                    configValue = defaultValue;
                }
            }else {
                configValue = baseConfig.getValue();
            }
        }
        configMap.put(tenantId + SPLIT_COLON + orgCode, configValue);
        return configValue;
    }

    private Map<String, String> buildHeader(String appId, InspectExceptionAlarmMesage alarmMessage, String signature) {
        Map<String,String> header = new HashMap<>();
        header.put(APP_ID, appId);
        header.put(ORG_CODE,alarmMessage.getOrgCode());
        header.put(TENANT_ID, alarmMessage.getTenentId().toString());
        header.put(SIGNATURE, signature);
        // TODO 待确认
        header.put(USER_ID, DEFAULT_USER_ID);
        header.put(USER_NAME, DEFAULT_USER_NAME);
        return header;
    }

}
